layui.define(["jquery",'vCache'], function (exports) {
    let vCache = layui.vCache,
        $ = layui.$;
    let http = new function () {
        this.get = function (url, data = {}) {
            return http.ajax({type: 'get', url: url, data: data})
        }
        this.post = function (url, data) {
            return http.ajax({type: 'post', url: url, data: data})
        }

        this.getHtml = function (url, callback) {
            let uri = url;
            if(layuimini.config.dev === true ){
                const v = new Date().getTime();
                uri = url.indexOf("?") > -1 ? url + '&v=' + v : url + '?v=' + v
            }
            $.get(uri, function (res) {
                callback(res)
            });
        }

        this.ajax = function (options) {
            let load;
            options.dataType = options.dataType || 'json'
            options.beforeSend = options.beforeSend || function (xhr) {
                load = layer.msg('加载中...')
                const x_token = vCache.sGet('X-token') || vCache.lGet('X-token');
                if (x_token) {
                    xhr.setRequestHeader('X-token', x_token)
                }
            }
            return $.ajax(options)
                .done(function (data,xhr,rep) {
                    if (data.code === 200) {
                        if (data.result != null && data.result.url != undefined) {
                            setTimeout(() => {
                                window.location = data.result.url;
                            }, 1200);
                        }
                        return ;
                    }else if( data.code === 203){
                        if(window.openBox){
                            layer.closeAll()
                        }
                        let msg = data.msg || '没有相关权限'
                        layer.msg(msg ,{time:5500})
                    }
                })
                .fail(function (err) {
                    let msg;
                    if(err.responseJSON){
                        msg = err.responseJSON.msg
                    } else             {
                        msg = err.responseText;
                    }
                    layer.alert(msg)
                })
                .always(function (res) {
                    layer.close(load);
                });
        }
    }

exports('http',http)
})